package com.zhouzj.task.springcloud.user.service;

import cn.hutool.core.util.IdUtil;
import com.zhouzj.task.springcloud.user.api.UserService;
import com.zhouzj.task.springcloud.user.domain.LagouToken;
import com.zhouzj.task.springcloud.user.domain.User;
import com.zhouzj.task.springcloud.user.repo.LagouTokenRepo;
import com.zhouzj.task.springcloud.user.repo.UserRepo;
import com.zhouzj.task.springcode.code.api.CodeService;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.dubbo.config.annotation.Service;

import javax.annotation.Resource;

/**
 * @Author: zhouzhijun
 * @Date: 2021/8/5 11:40
 */
@Service
public class UserServiceImpl implements UserService {

    @Resource
    private UserRepo userRepo;

    @Reference
    private CodeService codeService;

    @Resource
    private LagouTokenRepo lagouTokenRepo;

    @Override
    public Boolean register(String email, String password, String code) {
        Boolean valid = codeService.check(email, code);
        if (!Boolean.TRUE.equals(valid)) {
            throw new RuntimeException("验证码错误");
        }

        User user = new User();
        user.setEmail(email);
        user.setPassword(password);
        userRepo.save(user);

        return Boolean.TRUE;
    }

    @Override
    public Boolean registerCheck(String email) {
        return userRepo.existsByEmail(email);
    }

    @Override
    public String login(String email, String password) {
        Boolean success = userRepo.existsByEmailAndPassword(email, password);

        String token = IdUtil.getSnowflake().nextIdStr();
        LagouToken lagouToken = new LagouToken();
        lagouToken.setEmail(email);
        lagouToken.setToken(token);
        lagouTokenRepo.save(lagouToken);

        return token;
    }

    @Override
    public String info(String token) {
        LagouToken lagouToken = lagouTokenRepo.findFirstByToken(token);
        if (lagouToken == null) {
            throw new RuntimeException("登录已过期，请重新登录");
        }
        return lagouToken.getEmail();
    }
}
